import tkinter as tk
from tkinter import ttk, messagebox
import os
import random
import json
from datetime import datetime
import calendar
import pandas as pd


class HospitalExcelApp:
    HISTORY_FILE = "history.json"

    def __init__(self, root):
        self.root = root
        self.root.title("医院数据生成器")
        self.history = []

        # 创建文件存储目录
        self.flows_dir = "flows"
        os.makedirs(self.flows_dir, exist_ok=True)

        # 加载历史记录
        self.load_history()

        # 创建界面组件
        self.create_widgets()
        self.update_history_listbox()

    def create_widgets(self):
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 左侧输入区域
        input_frame = ttk.Frame(main_frame)
        input_frame.grid(row=0, column=0, sticky=tk.NSEW, padx=5)

        # 日期选择行
        ttk.Label(input_frame, text="选择年月：").grid(row=0, column=0, padx=5, pady=5)
        self.month_given = tk.StringVar(value=datetime.now().strftime("%Y-%m"))
        self.date_entry = ttk.Entry(input_frame, textvariable=self.month_given)
        self.date_entry.grid(row=0, column=1, padx=5, pady=5)

        # 医院数据输入行
        self.hospital_configs = [
            {"name": "信阳中心医院", "docs": "彭安厚"},
            {"name": "驻马店中心医院", "docs": "张艺涵 林永丽 董英豪 杨灿"},
            {"name": "南阳二院", "docs": "周琳 邓婧靓"}
        ]

        for i, config in enumerate(self.hospital_configs, 1):
            # 医院名称
            name_var = tk.StringVar(value=config["name"])
            ttk.Entry(input_frame, textvariable=name_var).grid(row=i, column=0, padx=5, pady=5)

            # 盒数标签
            ttk.Label(input_frame, text="盒数").grid(row=i, column=1, padx=5, pady=5)

            # 数量输入
            qty_var = tk.StringVar()
            ttk.Entry(input_frame, textvariable=qty_var).grid(row=i, column=2, padx=5, pady=5)

            # 医生列表
            doc_var = tk.StringVar(value=config["docs"])
            ttk.Entry(input_frame, textvariable=doc_var).grid(row=i, column=3, padx=5, pady=5)

            setattr(self, f"hospital{i}_name", name_var)
            setattr(self, f"hospital{i}_qty", qty_var)
            setattr(self, f"hospital{i}_docs", doc_var)

        # 右侧历史记录区域
        history_frame = ttk.Frame(main_frame)
        history_frame.grid(row=0, column=1, sticky=tk.NSEW, padx=5)

        ttk.Label(history_frame, text="历史记录").pack()
        self.history_listbox = tk.Listbox(history_frame, width=30, height=10)
        self.history_listbox.pack(fill=tk.BOTH, expand=True)
        self.history_listbox.bind("<Double-Button-1>", self.open_selected_file)

        btn_frame = ttk.Frame(history_frame)
        btn_frame.pack(pady=5)
        ttk.Button(btn_frame, text="打开选中", command=self.open_selected_file).pack(side=tk.LEFT, padx=2)

        # 底部按钮
        btn_frame = ttk.Frame(main_frame)
        btn_frame.grid(row=1, column=0, columnspan=2, pady=10)

        ttk.Button(btn_frame, text="确定", command=self.generate_data).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="取消", command=self.confirm_exit).pack(side=tk.LEFT)

        # 配置网格权重
        main_frame.columnconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(0, weight=1)

    def generate_filename(self):
        """生成带日期和随机数的文件名"""
        timestamp = datetime.now().strftime("%Y%m%d")
        rand_num = random.randint(1000, 9999)
        return f"{timestamp}_{rand_num}.xlsx"

    def generate_dates(self, year, month, n):
        """生成升序随机日期"""
        _, num_days = calendar.monthrange(year, month)
        days = sorted([random.randint(1, num_days) for _ in range(n)])
        return [datetime(year, month, day) for day in days]

    def generate_sheet_data(self, hospital_name, quantity, doctors):
        """根据医院生成不同格式的数据"""
        year, month = map(int, self.month_given.get().split('-'))
        dates = self.generate_dates(year, month, quantity)
        doctors_list = doctors.split()

        if hospital_name == "信阳中心医院":
            return pd.DataFrame({
                "药品名称": ["维A酸片(艾力可)"] * quantity,
                "规格": ["20mg*10片"] * quantity,
                "日期": [d.strftime("%Y-%m-%d") for d in dates],
                "数量": [1] * quantity,
                "医生": [random.choice(doctors_list) for _ in range(quantity)]
            })
        elif hospital_name == "驻马店中心医院":
            return pd.DataFrame({
                "日期": [d.strftime("%Y/%m/%d") for d in dates],
                "药品名称": ["维A酸片(艾力可)20mg/10片"] * quantity,
                "数量": [1] * quantity,
                "医生": [random.choice(doctors_list) for _ in range(quantity)]
            })
        elif hospital_name == "南阳二院":
            return pd.DataFrame({
                "药品名称": ["维A酸片(艾力可)20mg×10片"] * quantity,
                "日期": [d.strftime("%Y/%m/%d") for d in dates],
                "数量": [1] * quantity,
                "医生": [random.choice(doctors_list) for _ in range(quantity)]
            })

    def generate_data(self):
        try:
            filename = self.generate_filename()
            filepath = os.path.join(self.flows_dir, filename)

            # 验证日期格式
            datetime.strptime(self.month_given.get(), "%Y-%m")

            with pd.ExcelWriter(filepath) as writer:
                for i in range(1, 4):
                    hospital_name = getattr(self, f"hospital{i}_name").get()
                    quantity = int(getattr(self, f"hospital{i}_qty").get())
                    doctors = getattr(self, f"hospital{i}_docs").get()

                    if quantity <= 0:
                        raise ValueError("盒数必须大于0")
                    if not doctors.strip():
                        raise ValueError("医生列表不能为空")

                    df = self.generate_sheet_data(hospital_name, quantity, doctors)
                    df.to_excel(writer, sheet_name=hospital_name[:31], index=False)

            # 添加历史记录并保存
            self.history.insert(0, {
                "filename": filename,
                "path": filepath,
                "timestamp": datetime.now().isoformat()
            })
            self.save_history()
            self.update_history_listbox()

            os.startfile(filepath)
            messagebox.showinfo("成功", f"文件已生成：{filename}")
        except Exception as e:
            messagebox.showerror("错误", f"输入错误：{str(e)}")

    def load_history(self):
        """加载历史记录"""
        if os.path.exists(self.HISTORY_FILE):
            try:
                with open(self.HISTORY_FILE, 'r') as f:
                    self.history = json.load(f)
            except:
                self.history = []

    def save_history(self):
        """保存历史记录"""
        with open(self.HISTORY_FILE, 'w') as f:
            json.dump(self.history[:50], f)  # 最多保存50条记录

    def update_history_listbox(self):
        """更新历史记录列表"""
        self.history_listbox.delete(0, tk.END)
        for item in self.history:
            self.history_listbox.insert(tk.END, item["filename"])

    def open_selected_file(self, event=None):
        """打开选中的历史文件"""
        selection = self.history_listbox.curselection()
        if selection:
            index = selection[0]
            filepath = self.history[index]["path"]
            if os.path.exists(filepath):
                os.startfile(filepath)
            else:
                messagebox.showerror("错误", "文件不存在或已被删除")

    def confirm_exit(self):
        if messagebox.askyesno("确认退出", "确定要退出程序吗？"):
            self.root.destroy()


if __name__ == "__main__":
    root = tk.Tk()
    app = HospitalExcelApp(root)
    root.mainloop()